import { Input, Typography } from 'antd';
import React from 'react';
import { FormItem, YmForm } from 'ym-design';

const Dependencies2: React.FC = () => {
  const [form] = YmForm.useForm();
  return (
    <div style={{ maxWidth: '600px' }}>
      <div style={{ marginBottom: '30px' }}>
        <p style={{ fontSize: '12px', marginBottom: '10px' }}>
          Field.password2 依赖 Field.password,
          Field.undefined依赖Field.password2 。
        </p>
        <p style={{ fontSize: '12px', marginBottom: '10px' }}>
          Field.password onChange， 在
          Field.password2执行过onChage/initialValue!==undefined
          时，Field.undefined也会加载(reRender)
        </p>
      </div>
      <YmForm
        form={form}
        name="dependencies"
        autoComplete="off"
        style={{ maxWidth: 600 }}
      >
        <FormItem label="Password" name="password" rules={[{ required: true }]}>
          <Input />
        </FormItem>

        {/* Field */}
        <FormItem
          label="Confirm Password"
          name="password2"
          dependencies={['password']}
          rules={[
            {
              required: true,
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(
                  new Error('The new password that you entered do not match!'),
                );
              },
            }),
          ]}
        >
          <Input />
        </FormItem>

        {/* Render Props */}
        <FormItem noStyle dependencies={['password2']}>
          {() => {
            console.log('---FormItem[undefined]--reRender--');
            return (
              <Typography>
                <p>
                  Only Update when <code>password2</code> updated:
                </p>
                <pre>{JSON.stringify(form.getFieldsValue(), null, 2)}</pre>
              </Typography>
            );
          }}
        </FormItem>
      </YmForm>
    </div>
  );
};

export default Dependencies2;
